package br.unifor.cct.mia.mutation;

import java.awt.Point;
import java.util.List;

import br.unifor.cct.mia.dataenhancement.Attribute;
import br.unifor.cct.mia.dataenhancement.Structure;
import br.unifor.cct.mia.evolutionary.Genotype;
import br.unifor.cct.mia.ga.Ga;
import br.unifor.cct.mia.util.Methods;

public class MutationMeanMode implements Mutation {

	private Structure st;
	private String[] valores;
	private List positions;

	
	private void mutate(Ga ga) {        	
		double lbound, ubound;
		double x;

		for (int i = 0; i < ga.configurations.getPopsize(); i++) {

			for (int j = 0; j < ga.configurations.getNvars(); j++) {

				x = Methods.randDoubleValue(0, 1);
				if (x*100 < 50) {

					x = Methods.randDoubleValue(0, 1);
					if (x*100 < ga.configurations.getPmutation()*100) {
						lbound = ((Genotype)ga.population[i]).getLower(j);
						ubound = ((Genotype)ga.population[i]).getUpper(j);

						if (((Genotype)ga.population[i]).getInteger(j))
							((Genotype)ga.population[i]).setGene(Methods.randIntValue((int)lbound, (int)ubound), j);
						else
							((Genotype)ga.population[i]).setGene(Methods.randDoubleValue(lbound,ubound), j);
					}

				}
				else {

					x = Methods.randDoubleValue(0, 1);
					if (x*100 < ga.configurations.getPmutation()*100) {

						Point p = (Point)positions.get(j);
						Attribute att = st.getAttribute(p.y);

						if (att.getTipo().equalsIgnoreCase(Attribute.CONTINUOUS)) {	
							double valor = Double.parseDouble( valores[p.y] );							
							((Genotype)ga.population[i]).setGene(valor,j);
						}
						else {	
							String valor = valores[p.y];
							int posValor = st.getValues(att).indexOf(valor);
							((Genotype)ga.population[i]).setGene(posValor,j);
						}
					}					

				}
			}
		}
	}

	public Object execute(Object value) {
		Object[] o = (Object[])value;
		Ga ga = (Ga)o[0];
		positions = (List)o[1];
		valores = (String[])o[2];

		st = ga.getStructure();
		
		mutate(ga);        
		return ga.population;
	}



}
